#include "frmrcd_lsgcc.h"
#include "ui_frmrcd_lsgcc.h"
#include "rfidlib.h"
#include "qnamespace.h"
#include "QMessageBox"

using namespace Qt;
using namespace std;

FrmRcd_LSGCC::FrmRcd_LSGCC(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FrmRcd_LSGCC)
{
    ui->setupUi(this);
}

FrmRcd_LSGCC::~FrmRcd_LSGCC()
{
    delete ui;
}
void FrmRcd_LSGCC::create_alarm_record_view()
{
    ui->tbw_rcd_alarm->clear();
    QStringList strList;
    BYTE* szRate;
    int columns=2;

    strList<<tr("SID")<<tr("Type")<<tr("UID")<<tr("UserData")<<tr("Direction")<<tr("Date");
    columns=strList.length();
    szRate=new BYTE[columns]{1,1,4,5,2,4};

    ui->tbw_rcd_alarm->setColumnCount(columns);
    ui->tbw_rcd_alarm->setHorizontalHeaderLabels(strList);
    int wid=ui->tbw_rcd_alarm->size().width()-80;
    int szSum=0;
    for(int i=0;i<columns;i++)
    {
        szSum +=szRate[i];
    }
    for(int i=0;i<columns;i++)
    {
        ui->tbw_rcd_alarm->setColumnWidth(i,szRate[i]*wid/szSum);
    }
    delete[] szRate;

    ui->tbw_rcd_alarm->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tbw_rcd_alarm->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tbw_rcd_alarm->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
void FrmRcd_LSGCC::create_day_record_view()
{
    ui->tbw_rcd_day_total->clear();
    QStringList strList;
    BYTE* szRate;
    int columns=2;

    strList<<tr("In")<<tr("Out")<<tr("Date");
    columns=strList.length();
    szRate=new BYTE[columns]{1,1,2};

    ui->tbw_rcd_day_total->setColumnCount(columns);
    ui->tbw_rcd_day_total->setHorizontalHeaderLabels(strList);
    int wid=ui->tbw_rcd_day_total->size().width()-80;
    int szSum=0;
    for(int i=0;i<columns;i++)
    {
        szSum +=szRate[i];
    }
    for(int i=0;i<columns;i++)
    {
        ui->tbw_rcd_day_total->setColumnWidth(i,szRate[i]*wid/szSum);
    }
    delete[] szRate;

    ui->tbw_rcd_day_total->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tbw_rcd_day_total->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tbw_rcd_day_total->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
void FrmRcd_LSGCC::create_peopel_record_view()
{
    ui->tbw_rcd_people->clear();
    QStringList strList;
    BYTE* szRate;
    int columns=2;

    strList<<tr("Date")<<tr("Direction")<<tr("Count");
    columns=strList.length();
    szRate=new BYTE[columns]{3,1,1};

    ui->tbw_rcd_people->setColumnCount(columns);
    ui->tbw_rcd_people->setHorizontalHeaderLabels(strList);
    int wid=ui->tbw_rcd_people->size().width()-80;
    int szSum=0;
    for(int i=0;i<columns;i++)
    {
        szSum +=szRate[i];
    }
    for(int i=0;i<columns;i++)
    {
        ui->tbw_rcd_people->setColumnWidth(i,szRate[i]*wid/szSum);
    }
    delete[] szRate;

    ui->tbw_rcd_people->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tbw_rcd_people->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tbw_rcd_people->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
void FrmRcd_LSGCC::closeEvent(QCloseEvent *e)
{
    if(m_rdr->is_get_records)
        on_btn_get_record_stop_clicked();
}

void FrmRcd_LSGCC::paintEvent(QPaintEvent *e)
{
    if(!meta_sgnl_registed)//首次 加载完成
    {
        meta_sgnl_registed=true;
        init();
        qRegisterMetaType<vector<CRecord_Alarm>>("vector<CRecord_Alarm>");
        qRegisterMetaType<vector<CRecord_Day>>("vector<CRecord_Day>");
        qRegisterMetaType<vector<CRecord_RealTime>>("vector<CRecord_RealTime>");

        connect(m_rdr,SIGNAL(sgnl_lsgcc_get_records_end_loop(int)),this,SLOT(slot_lsgcc_get_records_end_loop(int)));
        connect(m_rdr,SIGNAL(sgnl_lsgcc_get_records(vector<CRecord_Alarm>,vector<CRecord_Day>,vector<CRecord_RealTime>,int,int,int,int,int,int)),
                   this,SLOT(slot_lsgcc_get_records(vector<CRecord_Alarm>,vector<CRecord_Day>,vector<CRecord_RealTime>,int,int,int,int,int,int)));
    }
}

void FrmRcd_LSGCC::init()
{
    create_alarm_record_view();
    create_day_record_view();
    create_peopel_record_view();
    ui->ckb_additional_alarm->setChecked(false);

    fontRcd.setFamily(QString("Arial"));
    fontRcd.setPixelSize(12);

    algnRcd = Qt::AlignHCenter|Qt::AlignVCenter;

    ui->btn_get_record_stop->setEnabled(false);
}
void FrmRcd_LSGCC::setReader(CAEDevice* m_rdr)
{
    this->m_rdr = (CRFID_LSG_CC*)m_rdr;
}

void FrmRcd_LSGCC::bind_rcd_alarm(vector<CRecord_Alarm> rcd_alarm)
{
    int rcd_count = rcd_alarm.size();
    if(rcd_count <= 0)
        return;

    QTableWidget *tbw_rcd = ui->tbw_rcd_alarm;
    int last_count=tbw_rcd->rowCount();

    tbw_rcd->setRowCount(last_count + rcd_count);
    CRecord_Alarm* tmp=NULL;
    int ulen=8;
    int idx=0;
    QString str;
    for (int i=0;i<rcd_count;i++) {
        tmp = &rcd_alarm[i];
        idx = i+last_count;


        //SID
        str.sprintf("%d",tmp->sid);
        tbw_rcd->setItem(idx,0,new QTableWidgetItem(str));

        //Type
        str.sprintf("%d",tmp->eventtype);
        tbw_rcd->setItem(idx,1,new QTableWidgetItem(str));

        //UID
        if(tmp->uidLen > 0)
        {
            if(tmp->uidLen != 9)//Not hf tag
                ulen = tmp->uidLen;
            const int strLen=(ulen+1)*2;
            CHAR c_uid[strLen];
            memset(c_uid,0,strLen);
            BytesToHexStr(tmp->uid,ulen,c_uid);
            str.sprintf("%s",c_uid);
            tbw_rcd->setItem(idx,2,new QTableWidgetItem(str));
        }
        else
            tbw_rcd->setItem(idx,2,new QTableWidgetItem(QString("%1").arg("")));

        //USER
        if(tmp->userLen>0)
        {
            ulen=tmp->userLen;
            const int strLen=(ulen+1)*2;
            CHAR c_user[strLen];
            memset(c_user,0,strLen);
            BytesToHexStr(tmp->user,ulen,c_user);
            str.sprintf("%s",c_user);
            tbw_rcd->setItem(idx,3,new QTableWidgetItem(str));
        }
        else
            tbw_rcd->setItem(idx,3,new QTableWidgetItem(QString("%1").arg("")));


        //Direction
        str.sprintf("%s",tmp->dFlag==0?"None":(tmp->dFlag==1?"In":"Out"));
        tbw_rcd->setItem(idx,4,new QTableWidgetItem(str));

        //Date
        str.sprintf("%02d%02d-%02d-%02d %02d:%02d:%02d",tmp->date[0],tmp->date[1],tmp->date[2],tmp->date[3],tmp->date[4],tmp->date[5],tmp->date[6]);
        tbw_rcd->setItem(idx,5,new QTableWidgetItem(str));

        tbw_rcd->item(idx,0)->setFont(this->fontRcd);
        tbw_rcd->item(idx,1)->setFont(this->fontRcd);
        tbw_rcd->item(idx,2)->setFont(this->fontRcd);
        tbw_rcd->item(idx,3)->setFont(this->fontRcd);
        tbw_rcd->item(idx,4)->setFont(this->fontRcd);
        tbw_rcd->item(idx,5)->setFont(this->fontRcd);
        tbw_rcd->item(idx,0)->setTextAlignment(algnRcd);
        tbw_rcd->item(idx,1)->setTextAlignment(algnRcd);
        tbw_rcd->item(idx,2)->setTextAlignment(algnRcd);
        tbw_rcd->item(idx,3)->setTextAlignment(algnRcd);
        tbw_rcd->item(idx,4)->setTextAlignment(algnRcd);
        tbw_rcd->item(idx,5)->setTextAlignment(algnRcd);
    }
    tbw_rcd->scrollToBottom();
}
void FrmRcd_LSGCC::bind_rcd_day(vector<CRecord_Day> rcd_day)
{

    int rcd_count = rcd_day.size();
    if(rcd_count <= 0)
        return;
    QTableWidget *tbw_rcd=ui->tbw_rcd_day_total;
    int last_count=tbw_rcd->rowCount();

    tbw_rcd->setRowCount(last_count + rcd_count);
    CRecord_Day* tmp=NULL;
    int idx=0;
    QString str;
    for (int i=0;i<rcd_count;i++) {
        tmp = &rcd_day[i];
        idx = i + last_count;

        //InCount
        str.sprintf("%d",tmp->inCount);
        tbw_rcd->setItem(idx,0,new QTableWidgetItem(str));

        //OutCount
        str.sprintf("%d",tmp->outCount);
        tbw_rcd->setItem(idx,1,new QTableWidgetItem(str));

        //Date
        str.sprintf("%02d%02d-%02d-%02d",tmp->date[0],tmp->date[1],tmp->date[2],tmp->date[3]);
        tbw_rcd->setItem(idx,2,new QTableWidgetItem(str));

        tbw_rcd->item(idx,0)->setFont(this->fontRcd);
        tbw_rcd->item(idx,1)->setFont(this->fontRcd);
        tbw_rcd->item(idx,2)->setFont(this->fontRcd);
        tbw_rcd->item(idx,0)->setTextAlignment(algnRcd);
        tbw_rcd->item(idx,1)->setTextAlignment(algnRcd);
        tbw_rcd->item(idx,2)->setTextAlignment(algnRcd);
    }
    tbw_rcd->scrollToBottom();
}
void FrmRcd_LSGCC::bind_rcd_realtime(vector<CRecord_RealTime> rcd_realtime)
{
    int rcd_count = rcd_realtime.size();
    if(rcd_count <= 0)
        return;

    QTableWidget *tbw_rcd = ui->tbw_rcd_people;

    int last_count=tbw_rcd->rowCount();

    tbw_rcd->setRowCount(last_count + rcd_count);
    CRecord_RealTime* tmp=NULL;
    int idx=0;
    QString str;
    for (int i=0;i<rcd_count;i++) {
        tmp = &rcd_realtime[i];
        idx = i + last_count;

        //Date
        str.sprintf("%02d%02d-%02d-%02d %02d:%02d:%02d",tmp->date[0],tmp->date[1],tmp->date[2],tmp->date[3],tmp->date[4],tmp->date[5],tmp->date[6]);
        tbw_rcd->setItem(idx,0,new QTableWidgetItem(str));

        //Direction
        str.sprintf("%s",tmp->direction==1?"In":"Out");
        tbw_rcd->setItem(idx,1,new QTableWidgetItem(str));

        //Count
        str.sprintf("%d",tmp->count);
        tbw_rcd->setItem(idx,2,new QTableWidgetItem(str));

        tbw_rcd->item(idx,0)->setFont(this->fontRcd);
        tbw_rcd->item(idx,1)->setFont(this->fontRcd);
        tbw_rcd->item(idx,2)->setFont(this->fontRcd);
        tbw_rcd->item(idx,0)->setTextAlignment(algnRcd);
        tbw_rcd->item(idx,1)->setTextAlignment(algnRcd);
        tbw_rcd->item(idx,2)->setTextAlignment(algnRcd);
    }
    tbw_rcd->scrollToBottom();
}

void FrmRcd_LSGCC::slot_lsgcc_get_records(vector<CRecord_Alarm> rcd_alarm,vector<CRecord_Day> rcd_day,vector<CRecord_RealTime> rcd_realtime,
                                          int total_in,int total_out,int day_in,int day_out,int use_time,int loop_count)
{
    QMutexLocker lock(&m_mutex);
    bind_rcd_alarm(rcd_alarm);
    if (AdditionFlags & CRFID_LSG_CC::Additional_PC_D)//取记录 天人流量
    {
        bind_rcd_day(rcd_day);
    }
    if (AdditionFlags & CRFID_LSG_CC::Additional_PC_R)//取当记录 天实时变化
    {
        bind_rcd_realtime(rcd_realtime);
    }
    if (AdditionFlags & CRFID_LSG_CC::Additional_PC_T)//取人数 进出馆累计总人数
    {
        ui->lbl_num_total_in->setText(QString("IN:%1").arg(total_in));
        ui->lbl_num_total_out->setText(QString("OUT:%1").arg(total_out));
    }
    if (AdditionFlags & CRFID_LSG_CC::Additional_PC_DR)//取人数 当天进出总
    {
        ui->lbl_num_day_in->setText(QString("IN:%1").arg(day_in));
        ui->lbl_num_day_out->setText(QString("OUT:%1").arg(day_out));
    }
    ui->lbl_info->setText(QString("Time: %1 ms\nLoop:%2").arg(use_time).arg(loop_count));
}
void FrmRcd_LSGCC::slot_lsgcc_get_records_end_loop(int iret)
{
    if(iret < 0 && ui->btn_get_record_stop->isEnabled())
    {
        ui->btn_get_record_stop->setEnabled(false);
        ui->btn_get_record_start->setEnabled(true);
        QMessageBox::critical(this,"End Get Records",QString("Get Records failed! err=%1").arg(iret),QMessageBox::Ok);
    }
    else {
        ui->btn_get_record_stop->setEnabled(false);
        ui->btn_get_record_start->setEnabled(true);
    }
}

void FrmRcd_LSGCC::on_btn_get_record_start_clicked()
{
    ui->btn_get_record_start->setEnabled(false);

    DWORD addt_flag=0;
    BYTE gate_id = 0;
    if (ui->ckb_additional_num_total->isChecked())
    {
        addt_flag |= CRFID_LSG_CC::Additional_PC_T;//取人数 进出馆累计总人数
    }
    if (ui->ckb_additional_num_day->isChecked())
    {
        addt_flag |= CRFID_LSG_CC::Additional_PC_DR;//取人数 当天进出总
    }
    if (ui->ckb_additional_rcd_day_total->isChecked())
    {
        addt_flag |= CRFID_LSG_CC::Additional_PC_D;//取记录 天人流量
    }
    if (ui->ckb_additional_rcd_people)
    {
        addt_flag |= CRFID_LSG_CC::Additional_PC_R;//取当记录 天实时变化
    }

    if (ui->ckb_additional_alarm->isChecked())
    {
        addt_flag |= CRFID_LSG_CC::Additional_Alarm;//使能报警,表示取记录的同时也触发安全门报警
        gate_id = ui->cmb_additional_alarm_gate_id->currentIndex();
    }
    AdditionFlags = addt_flag;
    int iret = m_rdr->start_get_records(AdditionFlags, gate_id);
    if(iret != NO_ERR)
    {
        QMessageBox::critical(this,"Start Get Records",QString("Start Get Records failed! err=%1").arg(iret),QMessageBox::Ok);
        ui->btn_get_record_start->setEnabled(true);
    }
    ui->btn_get_record_stop->setEnabled(true);
}

void FrmRcd_LSGCC::on_btn_get_record_stop_clicked()
{
    ui->btn_get_record_stop->setEnabled(false);
    m_rdr->stop_get_records();
}

void FrmRcd_LSGCC::on_btn_clear_clicked()
{
    QMutexLocker lock(&m_mutex);
    if(ui->cmb_clear_type->currentIndex() == 0)
    {
        ui->tbw_rcd_alarm->clearContents();
        ui->tbw_rcd_alarm->setRowCount(0);
        ui->tbw_rcd_day_total->clearContents();
        ui->tbw_rcd_day_total->setRowCount(0);
        ui->tbw_rcd_people->clearContents();
        ui->tbw_rcd_people->setRowCount(0);
    }
    else if(ui->cmb_clear_type->currentIndex() == 1)
    {
        ui->tbw_rcd_alarm->clearContents();
        ui->tbw_rcd_alarm->setRowCount(0);
    }
    else if(ui->cmb_clear_type->currentIndex() == 2)
    {
        ui->tbw_rcd_day_total->clearContents();
        ui->tbw_rcd_day_total->setRowCount(0);
    }
    else if(ui->cmb_clear_type->currentIndex() == 3)
    {
        ui->tbw_rcd_people->clearContents();
        ui->tbw_rcd_people->setRowCount(0);
    }
}

void FrmRcd_LSGCC::on_ckb_additional_num_total_stateChanged(int arg1)
{
    ui->grb_num_total->setEnabled(arg1==CheckState::Checked?true:false);
}

void FrmRcd_LSGCC::on_ckb_additional_num_day_stateChanged(int arg1)
{
    ui->grb_num_day->setEnabled(arg1==CheckState::Checked?true:false);
}

void FrmRcd_LSGCC::on_ckb_additional_rcd_day_total_stateChanged(int arg1)
{
    ui->grb_rcd_day_total->setEnabled(arg1==CheckState::Checked?true:false);
}

void FrmRcd_LSGCC::on_ckb_additional_rcd_people_stateChanged(int arg1)
{
    ui->grb_rcd_people->setEnabled(arg1==CheckState::Checked?true:false);
}

void FrmRcd_LSGCC::on_ckb_additional_alarm_stateChanged(int arg1)
{
    ui->cmb_additional_alarm_gate_id->setEnabled(arg1==CheckState::Checked?true:false);
}
